package com.hyj.serve.manage.controller;

import cn.hutool.core.util.StrUtil;
import com.hyj.serve.manage.configure.common.Result;
import com.hyj.serve.manage.configure.filter.LoginFilter;
import com.hyj.serve.manage.configure.properties.AppProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author HeYuJie
 * @date 2022/6/7
 */
@RestController
public class LoginController {

    private static final String LOGIN_COUNT = "login_count";
    private static final String LOGIN_TIME = "login_time";

    @Autowired
    private AppProperties appProperties;

    @PostMapping(value = "/login", consumes = MediaType.TEXT_PLAIN_VALUE)
    public Result<?> login(@RequestBody String password, HttpSession session){

        Object loginTimeAttr = session.getAttribute(LOGIN_TIME);
        if(loginTimeAttr != null){
            long lastLoginTime = (long) loginTimeAttr;
            if(System.currentTimeMillis() - lastLoginTime <= appProperties.getLoginInterval()){
                return Result.fail("重试次数超过"+appProperties.getLoginCount()+"次，请稍后再试").build();
            }
        }


        if(StrUtil.isEmpty(appProperties.getPassword()) || appProperties.getPassword().equals(password)){
            session.setAttribute(LoginFilter.IS_LOGIN, true);
            session.removeAttribute(LOGIN_COUNT);
            session.removeAttribute(LOGIN_TIME);
            return Result.ok().build();
        }


        session.setAttribute(LOGIN_TIME, System.currentTimeMillis());

        Object attribute = session.getAttribute(LOGIN_COUNT);
        int count = 0;
        if(attribute != null){
            count = (int) attribute;
        }

        if(count < appProperties.getLoginCount()){
            count++;
            session.setAttribute(LOGIN_COUNT, count);
        } else {
            return Result.fail("重试次数超过"+appProperties.getLoginCount()+"次，请稍后再试").build();
        }
        return Result.fail("登录失败"+ count +"次").build();
    }



}
